package com.qdsg.ysg.doctor.ui.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.provider.Settings;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Switch;
import android.widget.TextView;

import androidx.core.content.ContextCompat;

import com.hjq.shape.layout.ShapeFrameLayout;
import com.hjq.shape.layout.ShapeLinearLayout;
import com.hjq.shape.layout.ShapeRelativeLayout;
import com.hjq.shape.view.ShapeTextView;
import com.qdsg.ysg.doctor.R;
import com.qdsg.ysg.doctor.base.BaseApplication;
import com.qdsg.ysg.doctor.base.BaseFragment;
import com.qdsg.ysg.doctor.eventbus.Logout;
import com.qdsg.ysg.doctor.eventbus.VersionUpdateEvent;
import com.qdsg.ysg.doctor.nurse.activity.AtyAddCallPerson;
import com.qdsg.ysg.doctor.service.WebSocketService;
import com.qdsg.ysg.doctor.ui.MouldActivity;
import com.qdsg.ysg.doctor.ui.UpdatePasswordActivity;
import com.qdsg.ysg.doctor.ui.UserInfoActivity;
import com.qdsg.ysg.doctor.ui.activity.mine.DrugDirectoryActivity;
import com.qdsg.ysg.doctor.ui.activity.mine.SignatureSettingActivity;
import com.qdsg.ysg.doctor.ui.activity.mine.WxLoginActivity;
import com.qdsg.ysg.doctor.ui.dialog.GuideDialog;
import com.qdsg.ysg.doctor.ui.dialog.UpdateDialog;
import com.qdsg.ysg.doctor.util.HarmonyUtil;
import com.qdsg.ysg.doctor.util.ImageLoaderHelper;
import com.qdsg.ysg.doctor.util.ToastUtil;
import com.qdsg.ysg.doctor.util.UtilString;
import com.rest.business.RestProxy;
import com.rest.client.RestClient;
import com.rest.response.BaseResponse;
import com.rest.response.MineResponse;
import com.rest.response.VersionResponse;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Objects;

import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observer;
import io.reactivex.disposables.Disposable;
import jz.joyoung.robot.util.PreferencesHelper;

/**
 * Created by Administrator on 2018/5/25.
 */

public class MineFragment extends BaseFragment {

    @BindView(R.id.tv_name)
    TextView tv_name;
    @BindView(R.id.img_head)
    ImageView img_head;
    @BindView(R.id.btnSwitch)
    Switch btnSwitch;
    @BindView(R.id.btn_mould)
    ShapeLinearLayout btn_mould;
    @BindView(R.id.btn_setting)
    ShapeRelativeLayout btn_setting;
    @BindView(R.id.btn_signature_setting)
    ShapeLinearLayout btnSignatureSetting;
    @BindView(R.id.ll_head)
    LinearLayout llHead;
    @BindView(R.id.iv)
    ImageView iv;
    @BindView(R.id.tv_logout)
    ShapeTextView tvLogout;
    @BindView(R.id.ll_call_person)
    ShapeLinearLayout llCallPerson;
    @BindView(R.id.btn_drug_directory)
    ShapeLinearLayout btnDrugDirectory;
    @BindView(R.id.btn_check_version)
    ShapeFrameLayout btnCheckVersion;
    @BindView(R.id.tv_update_version)
    TextView tvUpdateVersion;
    @BindView(R.id.tv_version)
    TextView tvVersion;
    @BindView(R.id.dot)
    View dot;

    @SuppressLint("StaticFieldLeak")
    private static MineFragment mineFragment;

    @Override
    protected int getLayoutResource() {
        return R.layout.fragment_mine;
    }

    @Override
    protected void initView() {
        EventBus.getDefault().register(this);
        btnSwitch.setOnCheckedChangeListener((buttonView, isChecked) -> {
            if (isChecked) {
                accpetConsultation("1");
            } else {
                accpetConsultation("0");
            }
        });
    }

    @Override
    protected void initData() {
        getMineInfo();
    }


    @OnClick({R.id.ll_head, R.id.btn_mould, R.id.tv_logout, R.id.ll_call_person, R.id.btn_update_password, R.id.btn_signature_setting, R.id.btn_drug_directory, R.id.fl_update_version})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.ll_head:
                startActivity(new Intent(getActivity(), UserInfoActivity.class));
                break;
            case R.id.btn_mould:
                startActivity(MouldActivity.class);
                break;
            case R.id.tv_logout:
                EventBus.getDefault().postSticky(new Logout(6));
                mContext.stopService(new Intent(mContext, WebSocketService.class));
                RestClient.getInstance().token = "";
                RestClient.getInstance().clearSession();
                PreferencesHelper.getInstance().set(mContext, "token", "");
                startActivity(WxLoginActivity.class);
                mContext.finish();
                break;
            case R.id.ll_call_person:
                startActivity(AtyAddCallPerson.class);
                break;
            case R.id.btn_update_password:
                startActivity(UpdatePasswordActivity.class);
                break;
            case R.id.btn_signature_setting:
                startActivity(SignatureSettingActivity.class);
                break;
            case R.id.btn_drug_directory:
                startActivity(new Intent(mContext, DrugDirectoryActivity.class));
                break;
            case R.id.fl_update_version:
                getVersion();
                break;
            default:
                break;
        }
    }

    private void getVersion() {
        RestProxy.getInstance().getVersion(new Observer<VersionResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(VersionResponse versionResponse) {
                PackageManager pm = mContext.getPackageManager();
                PackageInfo pi;
                String versionName = "";
                int versionCode = 0;
                try {
                    pi = pm.getPackageInfo(mContext.getPackageName(), 0);
                    versionCode = pi.versionCode;
                    versionName = pi.versionName;
                } catch (PackageManager.NameNotFoundException e) {
                    e.printStackTrace();
                }
                if (versionResponse.data.vision > versionCode) {
                    if (HarmonyUtil.readPureModeState(mContext) == 1) {
                        showCodeDialog(versionResponse.data.url, versionResponse.data.isUpdate);
                    } else {
                        showPureModeDialog();
                    }
                } else {
                    ToastUtil.showToast(mContext, "已经是最新版本了！");
                }
                EventBus.getDefault().postSticky(new VersionUpdateEvent(versionResponse.data.url, versionName, versionResponse.data.vision > versionCode));
            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true)
    public void onVersionUpdate(VersionUpdateEvent updateEvent) {
        if (updateEvent.isUpdate) {
            dot.setVisibility(View.VISIBLE);
            tvUpdateVersion.setText("请下载最新版本");
        } else {
            dot.setVisibility(View.GONE);
            tvUpdateVersion.setText("检查更新");
        }
        tvVersion.setText(updateEvent.currentVersion);
    }

    private void showPureModeDialog() {
        GuideDialog guideDialog = GuideDialog.newInstance();
        guideDialog.setmListener(new GuideDialog.OnItemClickListener() {
            @Override
            public void onConfirm() {
                Intent intent = new Intent(Settings.ACTION_SETTINGS);
                startActivity(intent);
            }

            @Override
            public void onCancel() {

            }
        });
        guideDialog.show(getChildFragmentManager(), "guideDialog");
    }

    private void showCodeDialog(final String url, int isUpdate) {
        UpdateDialog mUpdateDialog = UpdateDialog.newInstance(isUpdate, false);
        mUpdateDialog.show(getChildFragmentManager(), "mUpdateDialog");
        mUpdateDialog.setmListener(new UpdateDialog.OnItemClickListener() {

            @Override
            public void onConfirm() {
                Intent intent = new Intent();
                intent.setData(Uri.parse(url));//Url 就是你要打开的网址
                intent.setAction(Intent.ACTION_VIEW);
                startActivity(intent); //启动浏览器
                Objects.requireNonNull(getActivity()).finish();
            }

            @Override
            public void onCancel() {

            }
        });
    }

    private void getMineInfo() {
        RestProxy.getInstance().getMineInfo(new Observer<MineResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(MineResponse mineResponse) {
                if (mineResponse.data.value == 1) {
                    btnSwitch.setChecked(true);
                } else {
                    btnSwitch.setChecked(false);
                }
            }

            @Override
            public void onError(Throwable e) {
                ToastUtil.onError(mContext, e);
            }

            @Override
            public void onComplete() {

            }
        });
    }


    private void accpetConsultation(String flag) {
        RestProxy.getInstance().accpetConsultation(flag, new Observer<BaseResponse>() {
            @Override
            public void onSubscribe(Disposable d) {

            }

            @Override
            public void onNext(BaseResponse baseResponse) {

            }

            @Override
            public void onError(Throwable e) {

            }

            @Override
            public void onComplete() {

            }
        });
    }


    @Override
    public void onResume() {
        super.onResume();
        tv_name.setText(BaseApplication.name);
        if (!UtilString.isEmpty(BaseApplication.avatar)) {
            ImageLoaderHelper.getInstance().GlideCircleImageLoader(mContext, BaseApplication.avatar, img_head);
        } else {
            if ("女".equals(BaseApplication.sex)) {
                img_head.setImageDrawable(ContextCompat.getDrawable(mContext, R.mipmap.icon_girl));
            } else {
                img_head.setImageDrawable(ContextCompat.getDrawable(mContext, R.mipmap.icon_boy));
            }
        }

        //isAudit 0 医生  1 药剂师  2 护士
        if (BaseApplication.isAudit != 0) {
            btn_mould.setVisibility(View.GONE);
            btn_setting.setVisibility(View.GONE);
        } else {
            btn_mould.setVisibility(View.VISIBLE);
            btn_setting.setVisibility(View.VISIBLE);
        }

        if (BaseApplication.isAudit == 0 || BaseApplication.isAudit == 1) {
            btnSignatureSetting.setVisibility(View.VISIBLE);
            llCallPerson.setVisibility(View.GONE);
            btnDrugDirectory.setVisibility(View.VISIBLE);
        } else {
            llCallPerson.setVisibility(View.VISIBLE);
            btnSignatureSetting.setVisibility(View.GONE);
            btnDrugDirectory.setVisibility(View.GONE);
        }
    }

    public static MineFragment newInstance() {
        if (mineFragment == null) {
            mineFragment = new MineFragment();
        }
        return mineFragment;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    public static void Logout() {
        mineFragment = null;
    }
}
